package com.ai.check;

import com.ai.common.constant.OperationPermissionConstant;
import com.ai.entity.security.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 深库security 自定义操作权限校验
 * @Author jiaok
 * @Date 2024-11-22 14:48
 */
@Component
public class SKExpressionRoot {


    /**
     * 是否具有操作摄像头的操作权限
     * @return
     */
    public boolean hasOperateCamera(){
        return hasOperate(OperationPermissionConstant.OPERATE_CAMERA);
    }

    /**
     * 是否具有操作板集modbus设备的操作权限
     * @return
     */
    public boolean hasOperateModbus(){
        return hasOperate(OperationPermissionConstant.BJ_MODBUS_DEVICE);
    }

    /**
     * 是否有xx权限
     * @param authority
     * @return
     */
    public  boolean hasPermission(String authority){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<GrantedAuthority> grantedAuthorities = sysUser.getGrantedAuthorities();
        List<String> permissionList = grantedAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

        return permissionList.contains(authority);

    }


    /**
     * 是否有操作权限
     * @param authority
     * @return
     */
    private   boolean hasOperate(String authority){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<GrantedAuthority> grantedAuthorities = sysUser.getGrantedAuthorities();
        List<String> permissionList = grantedAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

        if (!permissionList.contains(authority)) {
            throw new RuntimeException("您没有权限执行该操作");
        }

        return true;
    }




}
